<?php

namespace Mlym\CodeGeneration\ModelGeneration\Method;


use Mlym\CodeGeneration\ClassGeneration\MethodAbstract;
use Mlym\CodeGeneration\Middleware\Bean\Module\RelationBean;

class GetList extends MethodAbstract
{
    function addMethodBody()
    {
        //中间件数据
        $middlewareData = $this->classGeneration->getConfig()->getMiddlewareData();

        //当前模块表名称
        $alias = $middlewareData->getModule()->getAlias();

        $method = $this->method;

        //配置返回类型
        $method->setReturnType('array');

        //配置方法参数
        $method->addParameter('pageNo', 1)
            ->setType('int');
        $method->addParameter('pageSize', 10)
            ->setType('int');

        /**
         * 构建Alias
         */
        $aliasBody = $middlewareData->getModule()->getAlias()
            ? "\n	->alias('{$middlewareData->getModule()->getAlias()}')"
            : '';

        /**
         * 构建Join主体
         */
        $joinBody = '';
        if ($middlewareData->getModule()->getRelation()) {
            foreach ($middlewareData->getModule()->getRelation() as $index => $relationBean) {
                if ($relationBean instanceof RelationBean) {
                    $joinBody .= "\n	->join('{$relationBean->getName()} as {$relationBean->getAlias()}','{$relationBean->getCondition()}','{$relationBean->getJoinType()}')";
                }
            }
        }
        $methodBody = '';
        $methodBody .= <<<Body
        
\$list = \$this{$aliasBody}
    ->withTotalCount(){$joinBody}
	->order('{$alias}.' . \$this->schemaInfo()->getPkFiledName(), 'DESC')
    ->field('{$middlewareData->getViewFields()}')
    ->page(\$pageNo, \$pageSize)
    ->all();
\$total = \$this->lastQueryResult()->getTotalCount();
\$data = [
    'list' => \$list,
    'total' => \$total,
];
return \$data;
Body;
        //配置方法内容
        $method->setBody($methodBody);
    }

    function getMethodName(): string
    {
        return "getList";
    }

    function addComment()
    {
        $comment = <<<COMMENT
@param int \$pageNo 页码，默认1
@param int \$pageSize 每页数量，默认10
@return array
@throws Exception
@throws Throwable
COMMENT;
        $this->method->addComment($comment);

    }
}
